<?php


namespace Buu\Modules\EventSystem\Controllers;

use Adldap\AdldapException;
use Adldap\Models\ModelNotFoundException;
use App\Models\K8S;
use App\Models\MaxwellInstance;
use App\Models\DbInstance;
use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Facades\Admin as FAdmin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Hhz\Drone\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class MaxwellInstanceController extends AdminController
{
    protected $title = 'Maxwell实例';
    private const DEPLOY_CONFIG_File = "DroneConfigMap.json";
    public static array $aDroneConfig = [];


    public function __construct()
    {
        $dir = dirname( __DIR__) . "/Lib/" . self::DEPLOY_CONFIG_File;
        $sConfig = file_get_contents($dir);
        $configMap = json_decode($sConfig, true, 512, JSON_THROW_ON_ERROR);

        self::$aDroneConfig = $configMap['maxwell'];
    }

    public function index(Content $content)
    {
        $content->breadcrumb([
            'text' => $this->title
        ]);
        return parent::index($content);
    }

    protected function grid()
    {
        $grid = new Grid(new MaxwellInstance);
        $grid->paginate(50);
        $grid->disableFilter();
        $grid->disableExport();
        $grid->column('id', 'ID');
        $grid->column('project_id', '监听的数据库实例')->display(function () {
            return DbInstance::find($this->db_instance_id)->name;
        });
        $grid->column('include_db', '监听的库')->label()->width(360);
        $grid->column('rabbitmq_host', 'rabbitMq地址');
        $grid->column('rabbitmq_virtual_host', 'rabbitMq vhost');
        $grid->column('rabbitmq_exchange', 'rabbitMq exchange')->display(function () {
            return "maxwell-{$this->id}";
        });
        $grid->column('rabbitmq_rate', '消息生产速率（条/秒）');
        $grid->column('stateful_status', '运行状态')->label(K8S::WORKLOAD_STATUS_LABEL);
        $grid->actions(function ($actions) {
                $actions->append(
                    "<a style='color: green; margin-left: 10px;' href='maxwell-instance/operate-create/{$actions->row->id}'><i class='fa fa-cogs'></i>重载</a>"
                );
        });
        return $grid;
    }

    protected function form()
    {
        $form = new Form(new MaxwellInstance);
        $form->footer(function (Form\Footer $footer) {
            $footer->disableEditingCheck();
            $footer->disableCreatingCheck();
            $footer->disableViewCheck();
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
            $tools->disableView();
        });
        $form->select('db_instance_id', __('监听的数据库实例'))
            ->options(DbInstance::all()->pluck('name', 'id'))
            ->load('include_db', '/admin/EventSystem/db-instance/getDatabases')->required();
        $form->multipleSelect('include_db', '请选择监听的数据库')->options(function () {
            if ($this->db_instance_id) {
                return DbInstance::getDatabasesById($this->db_instance_id, 1);
            } else {
                return [];
            }
        })->required();
        $form->fieldset('maxwell设置', function (Form $form) {
            $form->text('maxwell_host', '配置存储数据库地址')->setWidth(4, 2)->required();
            $form->number('maxwell_port', '配置存储数据库端口')->setWidth(4, 2)->required();
            $form->text('maxwell_user', '配置存储数据库用户名')->setWidth(4, 2)->required();
            $form->password('maxwell_password', '配置存储数据库数据库密码')->setWidth(4, 2)->required();
            $form->text('maxwell_schema_database', '配置存储数据库名')->setWidth(4, 2)->default('maxwell')->required();
        });
        $form->fieldset('Rabbitmq设置', function (Form $form) {
            $form->text('rabbitmq_host', 'rabbitmq地址')->setWidth(4, 2)->required();
            $form->number('rabbitmq_port', 'rabbitmq端口')->setWidth(4, 2)->required();
            $form->text('rabbitmq_user', 'rabbitmq用户名')->setWidth(4, 2)->required();
            $form->password('rabbitmq_password', 'rabbitmq密码')->setWidth(4, 2)->required();
            $form->text('rabbitmq_virtual_host', 'rabbitmq vhost')->setWidth(4, 2)->required();
        });
        return $form;
    }

    public function operateCreate(Request $request, $id)
    {
        try {
            $branch = self::$aDroneConfig['branch'];
            $globalConfig = self::$aDroneConfig['global_config'];
            if (HhzEnv::isProduction()) {
                $globalConfig = $globalConfig['production'];
            } else {
                $globalConfig = $globalConfig['qa'];
            }
            //获取环境变量
            $parameters = ['MAXWELL_ID' => $id];
            $this->drone($globalConfig['target'], $parameters,
                self::$aDroneConfig['drone_address'],
                $branch);
        } catch (\Exception $e) {
            admin_toastr('操作失败' . $e->getMessage(), 'error', ['timeOut' => 5000]);
            return redirect('/admin/EventSystem/maxwell-instance');
        }
        admin_toastr('操作成功', 'success', ['timeOut' => 5000]);
        return redirect('/admin/EventSystem/maxwell-instance');
    }

    /**
     * 部署无人机
     */
    public function drone(
        string $target,
        array $parameters,
        string $sPromotePath,
        $branch = 'master'
    ) {
        Log::info('部署 :' . $sPromotePath . '--' . $branch . '--' . $target, $parameters);

        $drone = new Gateway(
            'https://drone.haohaozhu.me/api/',
            'nFIBGyqDaNe0N4iS33ir9SAPg54nVAQ3'
        );
        sleep(1);
        return $drone->Promote($sPromotePath, $target, $parameters, $branch);
    }
}